<?php


namespace app\community\controller;


use app\common\controller\Common;
use app\common\controller\Together;
use app\index\controller\Base;
use Couchbase\N1qlIndex;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Colony extends Base
{
    //景区列表
    public function index(){
        $name = '';
        $time = '';
        $area = '';
        $where = "1=1";
        $Together = new Together();
        $agent_city = $Together->ColonyCity();

        if(!empty($agent_city)){
            $where .=" and cityRegionId in ($agent_city)";
        }
        if(!empty($_GET['name'])){
            $where .= " and name like '%".$_GET['name']."%'";
        }
        if(!empty($_GET['time'])){
            $time = $_GET['time'];
            $serach = explode(' - ',$time);
            $starttime = strtotime($serach[0]);
            $endttime = strtotime($serach[1]." 23:59:59");
            $where .= " and '{$starttime}' < addtime and addtime<='{$endttime}'";
        }
        if(!empty($_GET['area'])){
            //获取区域信息
            $where1['name'] = ['like',"%".$_GET['area']."%"];
            $where1['level'] = ['elt',"3"];
            $region = Db::name("admin_region")->field("id,level,name,code")->where($where1)->find();
            $region_val = $region['id'];
            //查询代理区域
            $provinceWhere['province'] = ['in',$region_val];
            $cityWhere['city'] = ['in',$region_val];
            $areaWhere['area'] = ['in',$region_val];
            $provinceValue  = Db::name("admin_agent_city")->where($provinceWhere)->field("area,city,province")->select();
            $cityValue  = Db::name("admin_agent_city")->where($cityWhere)->field("area,city,province")->select();
            $areaValue  = Db::name("admin_agent_city")->where($areaWhere)->field("area,city,province")->select();
            $agent_city = array_merge($provinceValue,$cityValue,$areaValue);
            switch ($region['level']){
                case 1:
                    $area = array_unique(array_column($agent_city,"area"));
                    $city = array_unique(array_column($agent_city,"city"));
                    $province = array_unique(array_column($agent_city,"province"));
                    $area = implode($area,",");
                    $city = implode($city,",");
                    $province = implode($province,",");
                    $where .= " and (provinceId in ('$province') or fcityId in ('$city') or cityRegionId in ('$area'))";
                    break;
                case 2:
                    $area = array_unique(array_column($agent_city,"area"));
                    $city = array_unique(array_column($agent_city,"city"));
                    $area = implode($area,",");
                    $city = implode($city,",");
                    $where .= " and (fcityId in ('$city') or cityRegionId in ('$area'))";
                    break;
                case 3:
                    $area = array_unique(array_column($agent_city,"area"));
                    $area = implode($area,",");
                    $where .= " and (cityRegionId in ('$area'))";
                    break;
            }
        }
        $thisWechat = Session::get("thisWechat");
        $where .= " and (uniacid =".$thisWechat['id'].")";

        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_colony")->order("id desc")->where($where)->limit($start,$limit)->select();
                $count = Db::name("community_colony")->order("id desc")->where($where)->count("*");
                foreach ($list as $k=>$v){
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        $assign = [
            "name"=>$name,
            "time"=>$time,
            "area"=>$area
        ];
        $this->assign($assign);
        return $this->fetch('index');
    }

    //执行添加操作
    public function saveColony(){
        Db::startTrans();
        try{
            $rule = [
                ["provinceId", "require", "请选择省份"],
                ["fcityId", "require", "请选择城市"],
                ["cityRegionId", "require", "请选择区域"],
                ["streetCode", "require", "请选择街道"],
                ["address", "require", "请填写详细地址"],
                ["lng", "require", "请填写经纬度"],
                ["lat", "require", "请填写经纬度"],
                ["name", "require", "请填写景区名称"],
                ["principal", "require", "请填写负责人"],
                ["phone", "require", "请填写负责人电话"],
            ];
            $validate = new Validate($rule);
            $data = $this->request->post();
            $thisWechat = Session::get("thisWechat");
            $data['uniacid'] = $thisWechat['id'];
            if (!$validate->check($data)) {
                throw new Exception($validate->getError());
            }
            if(!empty($data['images'])){
                $images = $data['images'];
                $data['images'] = implode($images,",");
            }
            $common = new Common();
            if (!empty($data['phone'])) {
                $is_mobile = $common->is_mobile($data['phone']);
                if (!$is_mobile) {
                    throw new Exception("手机号码有误");
                }
            }
            if(!empty($data['id'])){
                $where['id'] = ['neq',$data['id']];
            }
            //判断景区是否已存在
            $where['name'] = $data['name'];
            $where['cityRegionId'] = $data['cityRegionId'];
            $detail = Db::name("community_colony")->where($where)->value("*");
            if(!empty($detail)){
                throw new Exception("该景区已存在，请勿重复添加");
            }
            //省份
            $province = Db::name("admin_region")->where(['id'=>$data['provinceId']])->field("name,code")->find();
            //城市
            $fcity = Db::name("admin_region")->where(['id'=>$data['fcityId']])->field("name,code")->find();
            //区域
            $cityRegion = Db::name("admin_region")->where(['id'=>$data['cityRegionId']])->field("name,code")->find();
            //街道
            $street = Db::name("admin_region")->where(['id'=>$data['streetCode']])->field("name,code")->find();
            $data['province'] = $province['name'];
            $data['fcity'] = $fcity['name'];
            $data['cityRegion'] = $cityRegion['name'];
            $data['street'] = $street['name'];
            $community = empty($data['community'])?[]:$data['community'];
            unset($data['community']);
            $area = "";
            if(empty($data['id'])){
                $data['addtime'] = time();
                $data['add_id'] = Session::get("id");
                $newid = Db::name("community_colony")->insertGetId($data);
                $communityData['addtime'] = time();
                $communityData['add_id'] = Session::get("id");
                $communityData['colony_id'] = $newid;
                foreach ($community as $k=>$v){
                    $communityData['community_id'] = $v;
                    //查询关联小区
                    $propertyName = Db::name("system_community")->where(['id'=>$v])->value("propertyName");
                    $area .= $propertyName . ",";
                    Db::name("community_colony_community")->insert($communityData);
                }
            }else{
                $newid= $data['id'];
                $data['updatetime'] = time();
                $data['updatetime'] = Session::get("id");
                Db::name("community_colony")->where(['id'=>$newid])->update($data);
                $oldcity = [];
                $oldcity = Db::name("community_colony_community")->where(['colony_id' => $newid])->field("id,community_id")->select();
                $oldcity = array_column($oldcity, "community_id");
                // 不包含执行删除
                foreach ($oldcity as $k=>$v){
                    if(!in_array($v,$community)){
                        Db::name("community_colony_community")->where(['community_id'=>$v,'colony_id'=>$newid])->delete();
                    }
                }
                foreach ($community as $k=>$v){
                    if(in_array($v,$oldcity)){
                       unset($community[$k]);
                    }
                }
                $communityData['addtime'] = time();
                $communityData['add_id'] = Session::get("id");
                $communityData['colony_id'] = $newid;
                foreach ($community as $k=>$v){
                    $communityData['community_id'] = $v;
                    //查询关联小区
                    $propertyName = Db::name("system_community")->where(['id'=>$v])->value("propertyName");
                    $area .= $propertyName . ",";
                    Db::name("community_colony_community")->insert($communityData);
                }
            }
            if(empty($data['id'])){
                $log['remark'] = "账户【" . Session::get("user_name") . "】新增景区【".$data['name']."】,景区id:".$newid."关联小区【".$area."】" ;
            }else{
                $log['remark'] = "账户【" . Session::get("user_name") . "】修改景区【".$data['name']."】信息,景区id:".$newid."关联小区【".$area."】" ;
            }
            $log['controller'] = "colony";
            $log['methods'] = "saveColony";
            $common->addLog($log);
            Db::commit();
            $black['code'] = 0;
            $black['msg'] = "添加成功";
        }catch (Exception $e){
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //添加景区
    public function addColony(){
        //获取代理商代理的区域
        $auto = Session::get("auto");
        //省份信息
        $where['level'] = 1;
        $region = Db::name("admin_region")->field("id,name,code")->where($where)->select();
        $assign = [
            "region" => $region,
        ];
        $this->assign($assign);
        if (!empty($_GET['id'])) {
            $detail = Db::name("community_colony")->where(['id'=>$_GET['id']])->find();
            //代理商、管理员标识
            $auto = Session::get("auto");
            if(!empty($auto)){
                //查询所代理的城市
                $agent_id = Session::get("id");
                $where1['agent_id'] = $agent_id;
                $where1['province'] = $detail['provinceId'];
                $value = Db::name("admin_agent_city")->where($where1)->field("province,city,area")->select();
                $value = array_column($value,"city");
                $value = array_unique($value);
                $where2['id'] = ['in',$value];
                //查询所代理的区域
                $agent_id = Session::get("id");
                $where1['agent_id'] = $agent_id;
                $where1['city'] = $detail['fcityId'];
                $value = Db::name("admin_agent_city")->where($where1)->field("province,city,area")->select();
                $value = array_column($value,"area");
                $value = array_unique($value);
                $where3['id'] = ['in',$value];
            }else{
                $code = Db::name("admin_region")->where(['id'=>$detail['provinceId']])->value('code');
                $where2['superior_code'] = $code;
                $code = Db::name("admin_region")->where(['id'=>$detail['fcityId']])->value('code');
                $where3['superior_code'] = $code;
            }
            //获取城市
            $fcity = Db::name("admin_region")->field("id,name,code")->where($where2)->select();
            //获取城市
            $cityRegion = Db::name("admin_region")->field("id,name,code")->where($where3)->select();
            //街道办
            $code = Db::name("admin_region")->where(['id'=>$detail['cityRegionId']])->value('code');
            $where4['superior_code'] = $code;
            $streetCode = Db::name("admin_region")->field("id,name,code")->where($where4)->select();
            $images = explode(",",$detail['images']);

            foreach ($images as $k=>$v){
                if(empty($v)){
                    unset($images[$k]);
                }
            }
            $this->assign("images",$images);

            $this->assign("fcity",$fcity);
            $this->assign("cityRegion",$cityRegion);
            $this->assign("streetCode",$streetCode);
            $this->assign("detail",$detail);
            return $this->fetch('edit');
        } else {
            return $this->fetch('create');
        }
    }

    /**
     * 删除景区
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/23/023
     */
    public function delColony(){
        try{
            $id = $_POST['id'];
            $colony = Db::name("community_colony")->where(['id'=>['in',$id]])->select();
            $res = Db::name("community_colony")->where(['id'=>['in',$id]])->delete();
            if(empty($res)){
                throw new Exception("删除失败");
            }
            Db::name("community_colony_community")->where(['colony_id'=>['in',$id]])->delete();
            Db::name("community_colony_manager_colony")->where(['colony_id'=>['in',$id]])->delete();
            $common = new Common();
            foreach ($colony as $k=>$v){
                $log['remark'] = "账号【" . Session::get("user_name") . "】删除景区【".$v['name']."】id【".$v['id']."】";
                $log['controller'] = "Colony";
                $log['methods'] = "delColony";
                $common->addLog($log);
            }
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }
}